<?php
namespace lib\redis;
use config\config;
use Redis;
/**
 * Ldy-item-RedisTool
 * Redis工具类
 * Class Tools
 * @package lib\redis
 */
class RedisTool{
    public static $redis;
    public static $redisTool;
    public static $rt;
    public static $key;

    public static function _init($index = 0){
        if (!self::$redisTool || !self::$redis) {
            self::$redisTool = new RedisTool();
            $data = config::get('redis');
            self::$redis = new Redis();
            self::$redis->connect($data['host'], $data['port']);
            self::$redis->auth($data['password']);
            self::$redis->select($index);
        }
        return self::$redisTool;
    }

    public function setKey($key){
        self::$key = $key;
        return $this;
    }

    public function getReturn(){
        return self::$rt;
    }

    public function getString(){
        self::$rt = json_decode(self::$redis->get(self::$key),true);
        return $this;
    }

    public  function setString($value){
        self::$rt = self::$redis->set(self::$key,json_encode($value,true));
        return $this;
    }

    public function setTime($time){
        self::$rt = self::$redis->expireAt(self::$key,time()+$time);
        return $this;
    }

    public function getListIndex($startIndex,$endIndex){

        self::$rt = self::$redis->lrange(self::$key,$startIndex,$endIndex);

        array_map(function($v){
            if (is_null(json_decode($v,true))){
                $v =  json_decode($v,true);
            }
            return $v;
        },self::$rt);

        return $this;
    }

    public function getListLeft(){
        self::$rt = self::$redis->lpop(self::$key);
        if (is_null(json_decode(self::$rt,true))){
            self::$rt =  json_decode(self::$rt,true);
        }
        return $this;
    }

    public function getListRight(){
        self::$rt = self::$redis->rpop(self::$key);
        if (is_null(json_decode(self::$rt,true))){
            self::$rt =  json_decode(self::$rt,true);
        }
        return $this;
    }

    public function setListLeft(){
        $args = func_get_args();
        self::$rt = self::$redis->lPush(self::$key,implode(',',$args));
        return $this;
    }
    public function setListRight(){
        $args = func_get_args();
        self::$rt = self::$redis->rPush(self::$key,implode(',',$args));
        return $this;
    }

    public function hSet($index,$value){
        self::$rt = self::$redis->hSet(self::$key,$index,$value);
        return $this;
    }

    public function hGet($index){
        self::$rt = self::$redis->hGet(self::$key,$index);
        return $this;
    }

    public function hGetAll(){
        self::$rt = self::$redis->hGetAll(self::$key);
        return $this;
    }

}